package projetjee

import groovy.time.TimeCategory

class User {

	transient springSecurityService

	String username
	String password
	String nom
	String prenom
	String mail
	String sexe
	String bio
	int vote = 20
	int nbVotant = 0
	int nbVotantPositif = 0
	int scoreTotal = 0
	int nbAmi = 0
	
	Date dateNaissance
	byte[] photoProfil
	
	boolean enabled = true
	boolean accountExpired
	boolean accountLocked
	boolean passwordExpired
	
	static hasMany = [ userTag: PhotoTaggee,
						relations: Relationship,
						relationsSubscriptions: Relationship,
						centreInteret: Activite]
	
	static constraints = {
		username blank: false, unique: true
		password blank: false
		
		nom blank: false
		prenom blank: false
		mail (email:true, nullable:true, blank:true, unique:true)
		sexe inList:['H','F']
		dateNaissance max: new Date(use(TimeCategory){16.years.ago.getTime()})
		
		photoProfil nullable:true, maxSize:1000000
		
		vote nullable:true
		nbVotant nullable:true
		scoreTotal nullable:true
		
	}
	
	static mappedBy = [relations: 'members',
                       relationsSubscriptions: 'subscribers']
	
	static mapping = {
		password column: '`password`'
		photoProfil type: "binary"
		relationsSubscriptions joinTable: 'user_relation_s'
		
	}

	Set<Role> getAuthorities() {
		UserRole.findAllByUser(this).collect { it.role } as Set
	}

	def beforeInsert() {
		encodePassword()
	}

	def beforeUpdate() {
		if (isDirty('password')) {
			encodePassword()
		}
	}

	protected void encodePassword() {
		password = springSecurityService.encodePassword(password)
	}
	
	String toString() {
		return nom+' '+prenom
	}
	

	
}
